<template>
    <div class="body_bgi box_1 full bgs_full relative" ref="home_box">
      <!-- header -->
      <big-screen-header headerName="鄂尔多斯细毛羊种羊场种养交易追溯信息" @globalSearch="globalSearch()" />

      <div class="w_full-60 h_full-100 m_0_auto ">
        <div class="w_full h_50 flex_row_between">
          <div class="w_full-200 h_50 flex_row_start color_fff lh_50">
            <div class="w_60 main_color">种羊场: </div>
            <div class="w_300">
              <el-select class="w_full_i" size="small" v-model="filterParams.farmId" clearable placeholder="请选择种羊场">
                <el-option
                  v-for="(item, index) in farmList" :key="index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="w_60 main_color ml_20">镇苏木: </div>
            <div class="w_200">
              <el-select class="w_full_i" size="small" v-model="filterParams.townId" clearable placeholder="请选择" @change="selectTown">
                <el-option
                  v-for="(item, index) in townList" :key="index"
                  :label="item.townName"
                  :value="item.townId"
                >
                </el-option>
              </el-select>
            </div>
            <div class="w_60 main_color ml_20">嘎查村: </div>
            <div class="w_200">
              <el-select class="w_full_i" size="small" v-model="filterParams.villageId" clearable placeholder="请选择">
                <el-option
                  v-for="(item, index) in villageList" :key="index"
                  :label="item.villageName"
                  :value="item.villageId">
                </el-option>
              </el-select>
            </div>
            <div class="w_60 main_color ml_20">牧户: </div>
            <div class="w_200">
              <el-input class="w_full_i" size="small" v-model="filterParams.nickName" clearable></el-input>
            </div>
            <div class="w_60 main_color ml_20">rfid: </div>
            <div class="w_200">
              <el-input class="w_full_i" size="small" v-model="filterParams.rfid" clearable></el-input>
            </div>
            <div class="w_60 main_color ml_20">交易年份: </div>
            <div class="w_100">
              <el-select class="w_full_i" size="small" v-model="filterParams.year" clearable placeholder="请选择交易年份">
                <el-option
                  v-for="(item, index) in yearList" :key="index"
                  :label="item.value"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>

          <div class="w_200 h_50 lh_50 flex_row_end gap_10">
            <div class="w_60 h_40 ml_10 main_color cursor" @click="search" >搜索</div>
            <div class="w_60 h_40 ml_10 main_color cursor" @click="handleExportData">导出</div>
          </div>
        </div>

        <div class="w_full h_full-120">
          <el-table 
            v-loading="isLoading" 
            element-loading-text="数据加载中..."
            :data="sellList" border style="width: 100%; height:100% !important" 
            :max-height="tableHeight"
            @select="selectRow"
          >
            <!-- 添加 选择框 -->
            <el-table-column type="selection" width="55" align="center" ></el-table-column>

            <el-table-column prop="farmName" label="种羊场" width="300" align="center">
              <template v-slot="scope">
                <span class=" cursor" @click="handleClickFarmName(scope.row)">{{ scope.row.farmName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="nickName" label="养殖户" width="200" align="center">
              <template v-slot="scope">
                <span class="color_blue cursor" @click="handleClickNickName(scope.row)">{{ scope.row.nickName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="townName" label="苏木(镇)" width="200" align="center">
              <template v-slot="scope">
                <span class=" cursor" @click="handleClickTownName(scope.row)">{{ scope.row.townName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="villageName" label="嘎查(村)" width="200" align="center">
              <template v-slot="scope">
                <span class=" cursor" @click="handleClickVillageName(scope.row)">{{ scope.row.villageName }}</span>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="totalCount" label="数量" width="200" align="center" /> -->
            <el-table-column prop="rfid" label="rfid" align="center" />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="w_full h_60 pt_20 text_right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="filterParams.curent"
            :page-size="filterParams.size"
            :page-sizes="[10, 50, 100, 200]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>

      <!-- Excel 导出 dialog -->
      <el-dialog
        title="数据导出中..."
        :visible.sync="exporting"
        width="30%"
      >
        <span>一共 {{ exportExcelData.totalPage }} 页，正在导出 {{ exportExcelData.curentPage }} 页，请稍后...</span>
      </el-dialog>
    </div>
</template>

<script>
  import CountFlop from '@/common/countFlop/index.vue';
  import defMixin from '@/mixins/def';
  import defImgMixin from '@/mixins/def-img';
  import componentsMixin from '@/mixins/components';

  import * as Excel from 'exceljs';
  import { saveAs } from 'file-saver';

  import { getTownList, getVillageList } from '@/api/base/base.js';
  import {  
    getFarmList, 
    getJiaoYiPage,
  } from '@/api/sheep/index.js';

  import { filePath } from "@/const"

  export default {
    name: 'Transaction-table',
    components: { CountFlop },
    mixins: [defMixin, defImgMixin, componentsMixin],
    data() {
      return {
        sheepList: [],
        tableHeight: window.innerHeight - 220,

        exporting: false,

        filePath: filePath,
        isLoading: false,

        filterParams: {
          farmId: '',
          townId: '',
          villageId: '',
          year: '',
          nickName: '',
          rfid: '',
          current: 1,
          size: 50,
        },
        total: 0,

        farmList: [],

        townList: [],                
        villageList: [],          

        sellList: [],

        exportExcelData: {
          curentPage: 1,
          totalPage: 1,
        },

        yearList: [
          { value: 2024 },
          { value: 2023 }
        ],

        selectedRows: []
      }
    },
    computed: {

    },
    created() {
      
    },
    async mounted() {
      let farmId = this.$route.params.farmId
      let townId = this.$route.params.townId
      let muHuId = this.$route.params.muHuId
      let muHuName = this.$route.params.muHuName
      let rfid = this.$route.params.rfid

      this.filterParams.farmId = farmId == 'null'? '' : farmId
      this.filterParams.townId = townId == 'null' ? '' : parseInt(townId)
      this.filterParams.muHuId = muHuId == 'null' ? '' : muHuId
      this.filterParams.nickName = muHuName == 'null' ? '' : muHuName
      this.filterParams.rfid = rfid == 'null' ? '' : rfid

      this.getTownList()

      if (townId) {
        this.getVillageList(townId)
      }

      // 获取 种羊场列表
      this.getFarmList()

      // 获取 种羊场 交易列表
      this.getJiaoYiPage(this.filterParams)
    },
    destroyed() {

    },
    methods: {
      // 获取  镇 苏木
      async getTownList() {
        let wsq_countyId = '150626000000'

        let res = await getTownList(wsq_countyId)
        try {
          if (res.code == 200) {
            this.townList = res.data
          }
        } catch(err) {
          console.log('获取所有镇数据失败 : ', err)
        }
      },
      
      // 获取 乡镇下的 所有 嘎查（村）
      async getVillageList(townId) {
        let res = await getVillageList(townId);
        try {
          if (res.code == 200) {
              this.villageList = res.data;
          }
        }
        catch (err) {
          console.log(err)
        }
      },

      // 种羊场 列表
      async getFarmList() {
        let res = await getFarmList()
        try {
          if (res.code == 200) {
            if (res.data && res.data.length) {
              this.farmList = res.data
            }
          }
        } catch(err) {
          console.log('获取种羊场列表失败 : ', err)
        }
      },

      // 交易信息
      async getJiaoYiPage(params) {
        this.sellList = []
        this.isLoading = true

        let res = await getJiaoYiPage(params)
        try {
          if (res.code == 200) {
            setTimeout(() => { 
              this.sellList = res.data
              this.total = res.total

              this.isLoading = false
            }, 500)
          }
        } catch(err) {
          console.log('获取交易信息列表失败 : ', err)
        }
      },

      selectTown(townId) {
        this.filterParams.villageId = ''
        this.getVillageList(townId)
      },

      // 搜索
      search() {
        this.getJiaoYiPage(this.filterParams)
      },

      // 点击 导出 按钮
      handleExportData() {
        this.exportData()
      },

      // 导出数据
      async exportData() {
        this.exporting = true
        let workbook = new Excel.Workbook();
        let worksheet = workbook.addWorksheet('我的工作表');

        worksheet.columns = [
          { header: '种羊场', key: 'farmName', width: 40, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          { header: '苏木镇', key: 'townName', width: 30, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          { header: '嘎查村', key: 'villageName', width: 30, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          { header: '姓名', key: 'nickName', width: 20, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          // { header: '身份证号码', key: 'idNum', width: 30, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          // { header: '一卡通号码', key: 'cardNum', width: 30, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          { header: '耳号', key: 'rfid', width: 20, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          // { header: '只数', key: 'totalCount', width: 10, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          // { header: '联系电话', key: 'phone', width: 20, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
          // { header: '备注', key: 'remark', width: 20, style: { font: { size: 16, }, alignment: { horizontal: "center" }, border: {} } },
        ];

        if (this.selectedRows.length) {
          for (let i in this.selectedRows) {
            worksheet.addRow(this.selectedRows[i]);
          }
        } else {
          let page = Math.ceil(this.total / this.filterParams.size)
          this.exportExcelData.totalPage = page

          for (let i = 0; i < page; i++) {
            this.exportExcelData.curentPage = i + 1
            let dataList = []
            let params = {
              farmId: this.filterParams.farmId || '',
              townId: this.filterParams.townId || '',
              villageId: this.filterParams.villageId || '',
              nickName: this.filterParams.nickName || '',
              rfid: this.filterParams.rfid || '',
              year: this.filterParams.year || '',
              current: i + 1,
              size: this.filterParams.size
            }

            let res = await getJiaoYiPage(params)
            try {
              if (res.code == 200) {
                dataList = res.data

                for (let i in dataList) {
                  worksheet.addRow(dataList[i]);
                }
              }
            } catch (err) {
              console.log('获取交易信息失败 : ', err);
            }
          }
        }

        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // 处理导出 Excel 文件名
        let farmName = ''
        let townName = ''
        let villageName = ''
        if (this.filterParams.farmId) {
          for(let i in this.farmList) {
            if (this.farmList[i].id == this.filterParams.farmId) {
              farmName = this.farmList[i].name
            }
          }
        }
        if (this.filterParams.townId) {
          for(let i in this.townList) {
            if (this.townList[i].townId == this.filterParams.townId) {
              townName = this.townList[i].townName
            }
          }
        }
        if (this.filterParams.villageId) {
          for(let i in this.villageList) {
            if (this.villageList[i].villageId == this.filterParams.villageId) {
              villageName = this.villageList[i].villageName
            }
          }
        }

        saveAs(blob, `${farmName || ''}-${townName||''}-${villageName || ''}-${this.nickName || ''}-${this.rfid || ''}-${this.year || ''}-交易信息.xlsx`);

        this.exporting = false

        this.$message({
          message: "数据导出成功！",
          type: 'success',
          duration: 1 * 1000
        })
      },

      // 点击 购买 记录
      clickSellItem(item) {
        this.$router.push({
          path: `/muHuPage/${item.townId}/${item.townName}/${item.villageId}/${item.villageName}/${item.muhuId}`
        })
      },

      // 监听 点击 种羊场
      clickFarm(item) {
        this.farmName = item.name
        this.farmId = item.id

        let params = {
          farmId: item.id,
          current: 1,
          size: 500,
        }
        this.getSellPage(params)

        // 获取 羊 分布
        this.getTownCattleCount(150626000000, item.id)
      },

       // 跳转到 牲畜详情页 
      clickAnimal(item) {
        this.$router.push(`/sheepDetail/${item.id}/${item.rfid}/null`)
      },

      handleCurrentChange(val) {
        this.filterParams.curent = val
        this.getJiaoYiPage(this.filterParams)
      },

      handleSizeChange(val) {
        this.filterParams.size = val
        this.getJiaoYiPage(this.filterParams)
      },

      // 点击 种羊场
      handleClickFarmName(item) {
        let path = `/zhongYangChang/${item.farmId}/${item.farmName}`
        this.goToPage(path)
      },

      // 跳转到牧户详情页
      handleClickNickName(item) {
        let path = `/muHuPage/${item.townId}/${item.townName}/${item.villageId}/${item.villageName}/${item.muhuId}`
        this.goToPage(path)
      },

      // 跳转到 镇苏木 页
      handleClickTownName(item) {
        let path = `/townPage/${item.townId}/${item.townName}`
        this.goToPage(path)
      },

      // 跳转到 嘎查村 页
      handleClickVillageName(item) {
        let path = `/villagePage/${item.townId}/${item.townName}/${item.villageId}/${item.villageName}`
        this.goToPage(path)
      },

      // 跳转页面 
      goToPage(val) {
        this.$router.push({
          path: val
        })
      },

      // 选择 表格 行
      selectRow(selection, row) {
        console.log(selection, row);

        this.selectedRows = selection
      },

      // 监听 Header.vue 搜索事件
      globalSearch(params) {
        console.log('监听 Header.vue 搜索事件 : ', params);
      }
    }
  }
</script>

<style lang="less">
  .el-pagination__total, .el-pagination__jump { color: #E4CFBB !important; }
</style>
